<template>
  <el-config-provider :locale="locale">
    <router-view></router-view>
  </el-config-provider>
</template>

<script lang="ts" setup>
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import en from 'element-plus/dist/locale/en.mjs'
import {computed, inject, onMounted, ref} from "vue"
import {checkLogin} from "@/core/util/app_util"
import {RouteRecordRaw, useRouter, useRoute} from "vue-router"
import {useStore} from 'vuex'

const store = useStore()    //获取store对象
const router = useRouter()
const route = useRoute()
const locale = computed(() => (ref('zh-cn').value === 'zh-cn' ? zhCn : en))
const $api = inject('$api')
const $post = inject('$post')

const menus = ref([])

onMounted(()=>{
  if(checkLogin()) {
    $post($api.route).then((res) => {
      menus.value = res.data.result.menus

      //处理路由
      handleAdminRoute()

      //跳转
      router.push(route.path)
    })
    return
  }

  //未登录跳转到登录页
  router.push("/login")
})

//处理路由
function handleAdminRoute(){
  if(menus.value==null && menus.value.length<=0)return

  for(var i=0;i<menus.value.length;i++){
    const menu:any = menus.value[i]

    addRouteItem(menu,"index")
  }
}

function addRouteItem(menu:any,parentName: string){
  const routeBaseInfo: RouteRecordRaw = {
    path: menu.url,
    name: menu.code,
    component: () => import('@/views'+menu.filePath),
    meta: {
      title: menu.title,
      icon: menu.icon,
      cache: menu.cache,
      type: menu.type,
      url: menu.url,
      addtab: true,
    },
  }

  if (parentName) {
    // for (let r of router.getRoutes()) {
    //   if(r.name=="index"){
    //     r.children.push(routeBaseInfo)
    //   }
    // }
    router.addRoute(parentName, routeBaseInfo)
  } else {
    router.addRoute(routeBaseInfo)
  }
}
</script>
